{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hands-on!\n",
    "\n",
    "Nessa prática, sugerimos alguns pequenos exemplos para você implementar sobre o Spark."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Apriorando o Word Count Memória Postumas de Brás Cubas\n",
    "\n",
    "Memórias Póstumas de Brás Cubas é um romance escrito por Machado de Assis, desenvolvido em princípio como folhetim, de março a dezembro de 1880, na Revista Brasileira, para, no ano seguinte, ser publicado como livro, pela então Tipografia Nacional.\n",
    "\n",
    "A obra retrata a escravidão, as classes sociais, o cientificismo e o positivismo da época. Dada essas informações, será que conseguimos idenficar essas características pelas palavras mais utilizadas em sua obra?\n",
    "\n",
    "Utilizando o dataset `Machado-de-Assis-Memorias-Postumas.txt`, elabore um `pipeline` utilizando `Estimators` e `Transformers` necessário do Spark para responder as perguntas abaixo. Não esqueça de utilizar `stopwords.pt` para remover as `stop words`!\n",
    "\n",
    "- Quais as 10 palavras mais frequentes?\n",
    "- Quais as 2-grams e 3-grams mais frequentes?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Bibliotecas\n",
    "from pyspark.ml import Pipeline\n",
    "from pyspark.ml.feature import Tokenizer, StopWordsRemover, CountVectorizer, NGram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "livro = sc.textFile(\"Machado-de-Assis-Memorias-Postumas.txt\")\n",
    "text = \"\"\n",
    "for line in livro.collect():\n",
    "    text += \" \" + line\n",
    "\n",
    "data = spark.createDataFrame([(0, text)], [\"id\", \"text\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10 Palavras Mais Frequentes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "tokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")\n",
    "remover = StopWordsRemover(inputCol=\"words\", outputCol=\"filtered\")\n",
    "count = CountVectorizer(inputCol=\"filtered\", outputCol=\"features\", vocabSize=10)\n",
    "\n",
    "pipeline = Pipeline(stages=[tokenizer, remover, count])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+---------------------------------------------------------------------------------------------+\n",
      "|features                                                                                     |\n",
      "+---------------------------------------------------------------------------------------------+\n",
      "|(10,[0,1,2,3,4,5,6,7,8,9],[2116.0,2115.0,1885.0,1720.0,1089.0,981.0,745.0,652.0,650.0,581.0])|\n",
      "+---------------------------------------------------------------------------------------------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "model = pipeline.fit(data).transform(data)\n",
    "model.select(\"features\").show(truncate=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### n-Grams"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")\n",
    "remover = StopWordsRemover(inputCol=\"words\", outputCol=\"filtered\")\n",
    "ngram = NGram(inputCol=\"filtered\", outputCol=\"ngrams\", n=2)\n",
    "count = CountVectorizer(inputCol=\"ngrams\", outputCol=\"features\", vocabSize=10)\n",
    "\n",
    "pipeline = Pipeline(stages=[tokenizer, remover, ngram, count])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+--------------------------------------------------------------------------------------+\n",
      "|features                                                                              |\n",
      "+--------------------------------------------------------------------------------------+\n",
      "|(10,[0,1,2,3,4,5,6,7,8,9],[160.0,158.0,139.0,136.0,128.0,117.0,111.0,107.0,88.0,81.0])|\n",
      "+--------------------------------------------------------------------------------------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "model = pipeline.fit(data).transform(data)\n",
    "model.select(\"features\").show(truncate=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ngram = NGram(inputCol=\"filtered\", outputCol=\"ngrams\", n=3)\n",
    "\n",
    "pipeline = Pipeline(stages=[tokenizer, remover, ngram, count])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+------------------------------------------------------------------------------+\n",
      "|features                                                                      |\n",
      "+------------------------------------------------------------------------------+\n",
      "|(10,[0,1,2,3,4,5,6,7,8,9],[23.0,22.0,20.0,17.0,15.0,15.0,14.0,14.0,11.0,11.0])|\n",
      "+------------------------------------------------------------------------------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "model = pipeline.fit(data).transform(data)\n",
    "model.select(\"features\").show(truncate=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TF-IDF com CountVectorizer\n",
    "\n",
    "No exemplo `TFIDF`, atualize a cell 15 para utilizar o Transformer `CountVectorizer`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "countVect = CountVectorizer(inputCol=\"rawFeatures\", outputCol=\"features\")\n",
    "countVectModel = countVect.fit(featurizedData)\n",
    "rescaledData = countVectModel.transform(featurizedData)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Apache Toree - PySpark",
   "language": "python",
   "name": "apache_toree_pyspark"
  },
  "language_info": {
   "codemirror_mode": "text/x-ipython",
   "file_extension": ".py",
   "mimetype": "text/x-ipython",
   "name": "python",
   "pygments_lexer": "python",
   "version": "3.5.2\n"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
